const requests = require('../../../config/request')
// pages/shop/list/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopLists: [],
    search: {
      search_key: '',
      is_hot: 0,
      cate_id2: '',
      page: 1
    },
    focus: true,
    loadTimeInterval: true,
    page: 1,
    pageEnd: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      search: Object.assign(this.data.search, {
        cate_id2: options.category || '',
        page: 1
      })
    })
    if(this.data.search.cate_id2) {
      this.shopList();
    } else {
      this.setData({
        focus: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  searchInputChange(e) {
    console.log(e)
    this.setData({
      shopLists: [],
      pageEnd: false,
      search: Object.assign(this.data.search, {
        search_key: e.detail.value,
        cate_id2: this.data.search.cate_id2,
        page: this.data.search.page
      })
    })
    if (e.detail.value){
      this.shopList();
    }
  },
  atBottom: function(){
    var that = this;
    if (this.data.pageEnd){
      // wx.showToast({
      //   title: '没有更多了~',
      //   icon: 'none',
      //   duration: 2000
      // })
      return
    }
    if (this.data.loadTimeInterval){
      that.setData({loadTimeInterval: false});

      that.setData({search: {
        search_key: that.data.search.search_key,
        is_hot: that.data.search.is_hot,
        cate_id2: that.data.search.cate_id2,
        page: that.data.search.page + 1
      }})
      that.shopList();

      setTimeout(function(){
        that.setData({loadTimeInterval: true});
      }, 1500);
    }
  },
  redirectToShop(e) {
    let shopId = e.currentTarget.dataset.shopId;
    console.log(shopId);
    wx.navigateTo({
      url: '../shop?shop_id=' + shopId,
    })
  },
  
  shopList() {
    wx.showLoading({
      title: '加载中',
    })
    requests.shopList(this.data.search).then(({list}) => {
      wx.hideLoading()
      if (list.length < 20){
        this.setData({pageEnd: true});
      }
      var newList = this.data.shopLists.concat(list);
      Array.isArray(list) && this.setData({
        shopLists: newList
      })
    })
  },
})